<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{padding: 0;margin: 0;}
        .box{
            width: 200px;
            height: 200px;
            background-color: #6ff;
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
    // 在页面中拖拽盒子移动 

    // 1. 先按下  a. 选中了盒子 b.记录了按下的位置   => onmousedown
    // 2. 再移动  盒子跟随鼠标相对于按下的位置 在页面中移动  => onmousemove
    // 3. 松开   盒子不在移动                      => onmouseup


    var box = document.getElementsByClassName("box")[0];


    box.onmousedown = function(e){
        var e = e || window.event;
        var posX = e.offsetX;
        var posY = e.offsetY;
        console.log(posX,posY);
        
        // 按下时绑定移动事件
        document.onmousemove = function(e){
            var e = e || window.event;
            console.log("鼠标移动");

            // 盒子跟随鼠标移动 (左上角)
            // var x = e.pageX;
            // var y = e.pageY;
            // console.log(x,y);

            // 盒子跟随鼠标相对于按下的位置移动
            var x = e.pageX - posX;
            var y = e.pageY - posY;
            console.log(x,y);


            box.style.left = x +"px";
            box.style.top = y +"px";


        }

        // 松开时 清除移动事件
        document.onmouseup = function(){
            document.onmousemove = null;
        }
    }
    










    /* box.onmousedown = function(e){
        var e = e || window.event;
        var posX = e.offsetX;
        var posY = e.offsetY;
        isPress = true;
    }
    document.onmousemove = function(){
        if(isPress == false) return false;
        console.log("鼠标移动");
    }
    document.onmouseup = function(){
        isPress = false;
    } */




</script>
</html>